package com.jeff.utils;

import android.content.Context;
import android.util.Log;

import java.lang.reflect.Field;

/**
 * author：duff
 * version：1.0.0
 * date：2017/8/31
 */
public class ResourceUtil {

    private static int getResId(Context context, String type, String field) {
        try {
            Class localClass = Class.forName(context.getPackageName() + ".R$" + type);
            Field localField = localClass.getField(field);
            return Integer.parseInt(localField.get(localField.getName()).toString());
        } catch (Exception localException) {
            Log.e("getIdByReflection error", localException.getMessage());
        }

        return 0;
    }

    public static int getId(Context context, String idStr) {
        return getResId(context, "id", idStr);
    }

    public static int getLayoutId(Context context, String idStr) {
        return getResId(context, "layout", idStr);
    }

    public static int getStringId(Context context, String idStr) {
        return getResId(context, "string", idStr);
    }

    public static int getStyleId(Context context, String idStr) {
        idStr = idStr.replaceAll("\\.", "_");
        return getResId(context, "style", idStr);
    }

    public static int[] getStyleableArr(Context context, String styleable) {
        try {
            Class localClass = Class.forName(context.getPackageName() + ".R$styleable");
            Field localField = localClass.getField(styleable);
            return (int[]) localField.get(localField.getName());
        } catch (Exception localException) {
            Log.e("getIdByReflection error", localException.getMessage());
        }

        return null;
    }

    public static int getStyleableAttrIndex(Context context, String styleable, String attrStr) {
        return getResId(context, "styleable", styleable + "_" + "" + attrStr);
    }

    public static int getDrawableId(Context context, String idStr) {
        return getResId(context, "drawable", idStr);
    }

    public static int getDimenId(Context context, String idStr) {
        return getResId(context, "dimen", idStr);
    }

    public static int getAttrId(Context context, String idStr) {
        return getResId(context, "attr", idStr);
    }

}
